<template>
  <base-container>
    <base-card class="pb24px" title="成员信息">
      <div class="header-info">
        <span class="header-info-title">初始登录密码：默认为手机号后6位。</span>
        <span class="header-info-tip"> *请提醒用户首次登录后立即修改，以防安全风险。</span>
      </div>
      <el-form ref="formRef" :model="userForm" :rules="userRules" label-position="top" label-width="80px">
        <el-row :gutter="16">
          <el-col :span="8">
            <el-form-item label="手机号码" prop="mobile">
              <el-input placeholder="请输入手机号码" v-model="userForm.mobile" :maxlength="11" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="成员姓名" prop="userName">
              <el-input placeholder="请输入成员姓名" v-model="userForm.userName" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="邮箱地址" prop="email">
              <el-input placeholder="请输入邮箱地址" v-model="userForm.email" />
            </el-form-item>
          </el-col>
          <el-col :span="13">
            <el-form-item label="组织架构" prop="deptId">
              <el-tree-select
                v-model="userForm.deptId"
                :data="deptTreeData"
                :props="{ children: 'children', label: 'deptName', value: 'id' }"
                :render-after-expand="false"
                placeholder="请选择组织架构"
                check-strictly
              ></el-tree-select>
            </el-form-item>
          </el-col>
          <el-col :span="13">
            <el-form-item class="device-tip" label="授信设备ID" prop="authDeviceId">
              <el-input type="textarea" :rows="4" placeholder="请输入授信设备ID" v-model="userForm.authDeviceId" />
            </el-form-item>
          </el-col>
          <el-col :span="13">
            <el-form-item label="备注信息" prop="remark">
              <el-input
                type="textarea"
                :rows="4"
                placeholder="请输入备注信息"
                v-model="userForm.remark"
                :maxlength="200"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item class="role-item" label="所属角色" label-position="left" :label-width="68">
              <el-button type="primary" plain @click="handleOpenAddRoleDialog">添加角色</el-button>
            </el-form-item>
            <div class="select-card" v-if="userForm.roles && userForm.roles.length">
              <div class="select-card-title">已添加角色</div>
              <div class="select-box">
                <div class="select-tag" v-for="(item, index) in userForm.roles" :key="item.id">
                  <span>{{ item.roleName }}</span>
                  <base-icon
                    class="select-tag__close"
                    name="iconfont-general gen-guanbi"
                    @click="() => userForm.roles.splice(index, 1)"
                  />
                </div>
              </div>
            </div>
          </el-col>
        </el-row>
      </el-form>
    </base-card>
    <!-- 选择角色 -->
    <select-role ref="selectRoleRef" v-model="userForm.roles" :role-list="roleList" title="添加角色" width="30%" />
    <!-- 底部按钮 -->
    <div class="form-btn center">
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" :disabled="submitLoading" :loading="submitLoading" @click="loadSubmitUserInfo">
        保存
      </el-button>
    </div>
  </base-container>
</template>

<script setup>
  import SelectRole from "../components/SelectRole.vue";

  // 获取路由实例
  const router = useRouter();

  onMounted(() => {
    // 获取角色列表
    loadGetRoleList();
    // 获取部门树数据
    loadGetDeptTree();
  });

  // 表单组件实例
  const formRef = ref({});

  // 成员表单
  const userForm = ref({
    userName: "", // 成员姓名
    mobile: "", // 手机号码
    email: "", // 邮箱地址
    authDeviceId: "", // 授信设备ID
    remark: "", // 备注信息
    roles: [], // 所属角色
    deptId: "", // 组织架构
  });

  // 成员表单校验规则
  const userRules = {
    userName: [
      { required: true, message: "请输入成员姓名", trigger: "blur" },
      { min: 1, max: 20, message: "成员姓名长度在 1 到 20 个字符", trigger: "blur" },
    ],
    mobile: [
      { required: true, message: "请输入手机号码", trigger: "blur" },
      { pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号码", trigger: "blur" },
    ],
    email: [
      { message: "请输入邮箱地址", trigger: "blur" },
      { type: "email", message: "请输入正确的邮箱地址", trigger: "blur" },
    ],
  };

  // 角色数据
  const roleList = ref([]);

  // 获取角色列表
  const loadGetRoleList = () => {
    Api.role.GetAllRoleList().then(res => {
      roleList.value = res.data || [];
    });
  };

  // 部门树数据
  const deptTreeData = ref();

  // 获取部门树数据
  const loadGetDeptTree = () => {
    Api.dept.GetDeptTree().then(res => {
      // 更新部门树数据
      deptTreeData.value = res.data || [];
    });
  };

  // select-role 组件实例
  const selectRoleRef = ref({});

  // 打开添加角色弹窗
  const handleOpenAddRoleDialog = () => {
    selectRoleRef.value.showDialog();
  };

  // 提交加载状态
  const submitLoading = ref(false);

  // 提交用户信息
  const loadSubmitUserInfo = () => {
    formRef.value.validate(valid => {
      if (!valid) return;
      // 开始加载
      submitLoading.value = true;
      // 提交用户信息
      Api.user
        .AddUser({
          ...userForm.value,
          roles: userForm.value.roles.map(item => item.id),
        })
        .then(() => {
          // 消息提示
          $msg.success("新增成功");
          // 关闭当前页面，跳转到用户列表
          router.replace({ path: ROUTE_PATHS.USER.LIST });
        })
        .finally(() => {
          // 结束加载
          submitLoading.value = false;
        });
    });
  };

  // 取消按钮，返回上级页面
  const handleCancel = () => router.replace({ path: ROUTE_PATHS.USER.LIST });
</script>
<style lang="scss" scoped>
  @use "@/views/permission/style/user.scss";
</style>
